<template>
  <div class="min-h-screen bg-gray-100 p-6">
    <h2 class="text-xl font-bold text-center mb-6">官网2后台管理</h2>

    <!-- 轮播图管理 -->
    <TableSection title="轮播图管理" :items="aData.web2_slider" :columns="sliderColumns" @add="addItem('slider')"
      @delete="deleteItem('slider', $event)" />

    <!-- 产品服务管理 -->
    <SectionWithHeader title="产品服务管理" :main-data="aData.web2_products" :items="aData.web2_products?.items"
      :item-columns="productColumns" @add="addItem('product')" @delete="deleteItem('product', $event)">
      <template #header-fields>
        <FormField label="标题" v-model="aData.web2_products.title" />
        <FormField label="描述" type="textarea" :rows="3" v-model="aData.web2_products.description" />
      </template>
    </SectionWithHeader>

    <!-- 解决方案管理 -->
    <SectionWithHeader title="解决方案管理" :main-data="aData.web2_solutions" :items="aData.web2_solutions?.items"
      :item-columns="solutionColumns" @add="addItem('solutions')" @delete="deleteItem('solutions', $event)">
      <template #header-fields>
        <FormField label="标题" v-model="aData.web2_solutions.title" />
        <FormField label="描述" type="textarea" :rows="3" v-model="aData.web2_solutions.description" />
        <!-- <FormField label="图片" v-model="aData.web2_solutions.image_url" /> -->
      </template>
    </SectionWithHeader>

    <!-- 新闻管理 -->
    <SectionWithHeader title="新闻管理" :main-data="aData.web2_news" :items="aData.web2_news?.items"
      :item-columns="newsColumns" @add="addItem('news')" @delete="deleteItem('news', $event)">
      <template #header-fields>
        <FormField label="标题" v-model="aData.web2_news.title" />
        <FormField label="描述" type="textarea" :rows="3" v-model="aData.web2_news.description" />
      </template>
    </SectionWithHeader>

    <!-- 关于我们 -->
    <SectionWithHeader title="关于我们" :main-data="aData.web2_about_us" :items="aData.web2_about_us?.stats"
      :item-columns="aboutUsColumns" @add="addItem('about_us')" @delete="deleteItem('about_us', $event)">
      <template #header-fields>
        <FormField label="标题" v-model="aData.web2_about_us.title" />
        <FormField label="图片" v-model="aData.web2_about_us.image_url" />
        <FormField label="描述标题" v-model="aData.web2_about_us.desc_title" />
        <FormField label="描述1" v-model="aData.web2_about_us.desc1" />
        <FormField label="描述2" v-model="aData.web2_about_us.desc2" />
        <FormField label="背景色" v-model="aData.web2_about_us.bg_color" />
      </template>
    </SectionWithHeader>

    <!-- 公司简介管理 -->
    <div class="bg-white shadow rounded-lg p-6" v-if="aData?.web2_company_intro">
      <h2 class="text-xl font-bold mb-6">公司简介管理</h2>
      <FormField label="标题" v-model="aData.web2_company_intro.title" />
      <FormField label="背景色" v-model="aData.web2_company_intro.bg_color" />
      <FormField label="描述" type="textarea" :rows="6" v-model="aData.web2_company_intro.description" />
    </div>

    <button class="mt-6 bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700" @click="saveData">保存</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
const { getAdminData, updateHomeData } = useAdminApi()
import TableSection from '@/components/admin/TableSection.vue'
import SectionWithHeader from '@/components/admin/SectionWithHeader.vue'
import FormField from '@/components/admin/FormField.vue'

definePageMeta({
  layout: 'minimal',
  showHeader: false
});
// 数据定义
const aData = ref({})

// 列配置
const sliderColumns = [
  { key: 'title', label: '标题', type: 'text' },
  { key: 'bg_color', label: '背景颜色', type: 'text' },
  { key: 'description', label: '背景图', type: 'text' },
  { key: 'image_url', label: '图片', type: 'text' },
  { key: 'sort_order', label: '排序', type: 'number' }
]

const productColumns = [
  { key: 'title', label: '标题', type: 'text' },
  { key: 'description', label: '描述', type: 'text' },
  { key: 'image_url', label: '图片', type: 'text' },
  { key: 'features', label: '描述字符（逗号分割）', type: 'text' },
  { key: 'sort_order', label: '排序', type: 'number' }
]

const solutionColumns = [
  { key: 'title', label: '标题', type: 'text' },
  { key: 'description', label: '描述', type: 'text' },
  { key: 'image_url', label: '图片', type: 'text' },
  { key: 'sort_order', label: '排序', type: 'number' }
]

const newsColumns = [
  { key: 'title', label: '标题', type: 'text' },
  { key: 'description', label: '描述', type: 'text' },
  { key: 'image_url', label: '图片', type: 'text' },
  { key: 'publish_date', label: '日期', type: 'date' },
  {
    key: 'tag',
    label: '标签',
    type: 'select',
    options: [
      { value: 'company_news', label: '公司新闻' },
      { value: 'product_update', label: '产品更新' },
      { value: 'activity', label: '活动' }
    ]
  }
]

const aboutUsColumns = [
  { key: 'title', label: '标题', type: 'text' },
  { key: 'value', label: '描述', type: 'text' },
  { key: 'sort_order', label: '排序', type: 'number' }
]

function getNested(obj, path) {
  return path.split('.').reduce((o, k) => (o || {})[k], obj)
}

// 添加项
const addItem = (type) => {
  const newId = Date.now()
  const templates = {
    slider: {
      title: '',
      description: '',
      image_url: '',
      bg_color: '',
      sort_order: 0
    },
    product: {
      product_id: aData.value.web2_products?.id || 1,
      title: '',
      description: '',
      image_url: '',
      sort_order: 0
    },
    news: {
      news_id: aData.value.web2_news?.id || 1,
      title: '',
      description: '',
      image_url: '',
      publish_date: new Date().toISOString().slice(0, 10),
      tag: 'company_news',
      sort_order: 0
    },
    about_us: {
      about_id: aData.value.web2_about_us?.id || 1,
      title: '',
      value: 0,
      sort_order: 0
    },
    solutions: {
      solution_id: aData.value.web2_solutions?.id || 1,
      title: '',
      description: '',
      image_url: '',
      sort_order: 0
    }
  }

  const path = getDataPath(type)
  const arr = getNested(aData.value, path)
  if (arr && Array.isArray(arr)) {
    arr.push(templates[type])
  }
}

// 删除项
const deleteItem = (type, id) => {
  if (!confirm('确定要删除此项吗?')) return

  const path = getDataPath(type)
  const arr = getNested(aData.value, path)
  if (arr && Array.isArray(arr)) {
    const idx = arr.findIndex(item => item.id === id)
    if (idx !== -1) arr.splice(idx, 1)
  }
}

// 获取数据路径
const getDataPath = (type) => {
  const paths = {
    slider: 'web2_slider',
    product: 'web2_products.items',
    news: 'web2_news.items',
    about_us: 'web2_about_us.stats',
    solutions: 'web2_solutions.items'
  }
  return paths[type]
}

const saveData = async () => {
  try {
    // 这里可以调用API保存数据
    console.log('保存数据:', aData.value)
    // 假设有一个saveAdminData函数来保存数据
    await updateHomeData(aData.value)
  } catch (error) {
    console.error('保存数据失败:', error)
  }
}

// 初始化数据
onMounted(async () => {
  aData.value = await getAdminData()
})
</script>